/* eslint quotes: 0 */
import React, {Component} from "react";
import {
    Dimensions,
    StyleSheet,
    View,
    Text,
    Button,
    StatusBar,
    TouchableOpacity,
    Image,
    TextInput,
    FlatList,
    ToastAndroid,
    DeviceEventEmitter,
} from "react-native";
import {color} from "../../widget/color";
import SafeAreaView from 'react-native-safe-area-view';

import SelectRebateCountDown from '../../widget/select/SelectRebateCountDown'
import {Heading1, Heading2, Heading3, Paragraph, Tip, Tip2, Tip3} from "../../widget/Text";
// const Realm = require('realm');
import {fetchGetRequest} from "../../api/NetworkTool";
import api from "../../api/api";
import method from "../../api/method";
const width = Dimensions.get(`window`).width;
import CornerLabel from 'react-native-smart-corner-label'
export default class SearchResultScene extends Component<> {

    static navigationOptions = ({navigation}: any) => ({
        header: null,
    });

    constructor(props) {
        super(props);

        this.state = {
            search_text: '',
            teachers: [],//教师数据集合
            teachers_size: 0,//教师数据结果数
            common_courses: [],//公开课数据集合
            common_courses_size: 0,//公开课数据结果数
            courses: [],//精品课数据集合
            courses_size: 0,//精品课数据结果集
            text_height: 0,
        };

        DeviceEventEmitter.emit('async', this.props.navigation.state.params.keyword);
    }

    componentDidMount() {

        this.requestNetData(this.props.navigation.state.params.keyword)

    }

    requestNetData(keyword) {
        fetchGetRequest(api.searchInfo, method.get, {keyword: keyword})
            .then(res => {
                console.log(res)

                let teachers_list = this.mapTeacherData(res.teachers)
                let common_courses_list = this.mapCommonData(res.common_courses)
                let courses_list = this.mapCoursesData(res.courses)
                this.setState({
                    teachers: teachers_list,
                    teachers_size: teachers_list.length,
                    common_courses: common_courses_list,
                    common_courses_size: common_courses_list.length,
                    courses: courses_list,
                    courses_size: courses_list.length,
                })
            })
            .catch(err => {

            })
    }

    /**
     * 解析教师数据
     * @param teachers
     * @returns {Object|*|{}|Array}
     */
    mapTeacherData = (teachers) => {
        let dataList = teachers.map((teacher) => {
            return {
                id: teacher.id,
                age: teacher.age,
                image: teacher.image,
                shot_introdece: teacher.shot_introdece,
                name: teacher.name,
                subject: teacher.subject,
            }
        })
        return dataList
    }

    /**
     * 解析公开课数据
     * @param common_datas
     * @returns {Object|*|{}|Array}
     */
    mapCommonData = (common_datas) => {
        let dataList = common_datas.map((common_data) => {
            return {
                id: common_data.id,
                image: common_data.image,
                lesson_url: common_data.lesson_url,
                start_date: common_data.start_date,
                teacher: common_data.teacher,
                teacher_image: common_data.teacher_image,
                title: common_data.title,
                buys: common_data.buys,
                totals: common_data.totals,
            }
        })
        return dataList
    }

    /**
     * 解析精品课数据
     * @param courses
     * @returns {Object|*|{}|Array}
     */
    mapCoursesData = (courses) => {
        let dataList = courses.map((course) => {
            return {
                end_date: course.end_date,
                id: course.id,
                master_teacher: course.master_teacher,
                price: course.price,
                amount: course.amount,
                remains: course.remains,
                start_date: course.start_date,
                subject: course.subject,
                tag: course.tag,
                title: course.title,
                buys: course.buys,
                totals: course.totals,
                tutor_teacher: course.tutor_teacher,
            }
        })
        return dataList
    }

    render() {
        return (
            <SafeAreaView style={ styles.container }>
                <View style={ styles.header}>
                    <TouchableOpacity onPress={()=>{this.goBack()}}>
                        <Image style={styles.imageBack} source={require('../../../res/img/gobal_back.png')}/>
                    </TouchableOpacity>

                    <TextInput
                        placeholder={this.props.navigation.state.params.keyword}
                        style={styles.inputStyle}
                        placeholderTextColor="#999999"
                        underlineColorAndroid='transparent'// 下划线透明
                        clearButtonMode="while-editing"
                        onFocus={() =>this.goBack()} //选中文本框
                    />
                    <TouchableOpacity
                        style={styles.btnSearch}>
                        <Text style={{color:'#7D7D7D',fontSize:12,}}>搜索</Text>
                    </TouchableOpacity>
                </View>
                <FlatList
                    backgroundColor='#F9F9F9'
                    data={this.state.courses}
                    keyExtractor={(item, index) => index}
                    renderItem={this.renderListItem}
                    ListHeaderComponent={this.renderHistoryHeader}
                />
            </SafeAreaView>
        );
    }

    /**
     * 头部渲染
     * @returns {XML}
     */
    renderHistoryHeader = () => {
        return (
            <View style={{backgroundColor:'#f9f9f9'}}>

                {this.checkVisible(1)}

                <View style={{marginBottom:15}}>
                    <FlatList
                        backgroundColor='#F9F9F9'
                        data={this.state.teachers}
                        keyExtractor={(item, index) => index}
                        renderItem={this.renderTeacherItem}
                    />
                </View>

                {this.checkVisible(2)}

                <FlatList
                    backgroundColor='#F9F9F9'
                    data={this.state.common_courses}
                    keyExtractor={(item, index) => index}
                    renderItem={this.renderTagItem}
                    horizontal={true}
                    showsHorizontalScrollIndicator={false}
                />

                {this.checkVisible(3)}

            </View>
        )
    }

    //判断标题是否显示
    checkVisible(type) {

        if (type == 1) {
            if (this.state.teachers_size > 0) {
                return <View
                    style={{marginLeft:15,justifyContent:'space-between',flexDirection:'row',alignItems:'center',marginTop:15, backgroundColor:'#F9F9F9'}}>
                    <Text style={styles.searchLeft}>老师</Text>
                    <View style={styles.score}>
                        <Text style={{fontSize:10,color:'white'}}>{this.state.teachers_size}</Text>
                    </View>
                </View>
            } else {
                return <View>
                </View>
            }
        } else if (type == 2) {
            if (this.state.common_courses_size > 0) {
                return <View
                    style={{marginLeft:15,justifyContent:'space-between',flexDirection:'row',alignItems:'center',backgroundColor:'#F9F9F9'}}>
                    <Text style={styles.searchLeft}>公开课</Text>
                    <View style={styles.score}>
                        <Text style={{fontSize:10,color:'white'}}>{this.state.common_courses_size}</Text>
                    </View>
                </View>
            } else {
                return <View>
                </View>
            }
        } else if (type == 3) {
            if (this.state.courses_size > 0) {
                return <View
                    style={{marginLeft:15,justifyContent:'space-between',flexDirection:'row',alignItems:'center',marginTop:15,backgroundColor:'#F9F9F9'}}>
                    <Text style={styles.searchLeft}>精选课</Text>
                    <View style={styles.score}>
                        <Text style={{fontSize:10,color:'white'}}>{this.state.courses_size}</Text>
                    </View>
                </View>
            } else {
                return <View>
                </View>
            }
        }


    }

    /**
     * 教师列表Item
     * @param rowData
     * @returns {XML}
     */
    renderTeacherItem = (rowData: any) => {
        let item = rowData.item;
        console.log({rowData})
        return (
            <TouchableOpacity onPress={()=>this.goToTeacherDetail(item.id)}>
                <View style={styles.cell_container2}>

                    <Image source={{uri:item.image}}
                           style={{width:80,height:80,alignItems:'center',justifyContent:'center',borderRadius:8,marginTop:10,marginLeft:10}}/>

                    <View style={{flexDirection:'column'}}>
                        <View style={{flexDirection:'row',alignItems:'center',marginTop:10,marginLeft:10}}>
                            <Text
                                style={{fontSize:13,color:'rgba(0,0,0,0.8)',fontWeight:'bold',}}>{item.name}</Text>
                            <View
                                style={{backgroundColor:'#DB3843',width:24,height:12,marginLeft:12,alignItems:'center',justifyContent:'center'}}>
                                <Text style={{color:'white',fontSize:10,}}>{item.subject}</Text>
                            </View>
                        </View>
                        <Text
                            style={{fontSize:11,color:'rgba(0,0,0,0.8)',marginLeft:10,marginTop:8,flex:1,marginRight:100,height:28}}
                            numberOfLines={2}>{item.shot_introdece == null ? '暂无介绍' : item.shot_introdece}</Text>


                        <View style={{flexDirection:'row' ,justifyContent: 'space-between'}}>
                            <Text style={{color:'#999999',fontSize:11,marginBottom:14,marginLeft:10}}
                                  numberOfLines={1}>{item.age}年教学经验</Text>
                            <View style={{width:80}}/>
                            <TouchableOpacity style={styles.submit_btn}
                                              onPress={() => this.goToTeacherDetail(item.id)}>
                                <Text style={{color:'white',fontSize:10,}}>进入老师主页</Text>
                            </TouchableOpacity>
                        </View>

                    </View>
                </View>
            </TouchableOpacity>
        )
    }

    /**
     * 跳转教师主页
     * @param id
     */
    goToTeacherDetail(id) {
        this.props.navigation.navigate('teacherHomeScene', {'teacher_id': id})
    }

    /**
     * 公开课列表Item
     * @param rowData
     * @returns {XML}
     */
    renderTagItem = (rowData: any) => {

        let item = rowData.item;

        let start_time = item.start_date.substr(5, 5).replace('-', '月') + '日'
        // let end_time = item.end_date.substr(5,5).replace('-','月')+'日'
        var showText = ''
        var show_txt = ''
        if (item.buys >= item.totals * 0.8 && item.buys < item.totals) {
            showText = item.remains + '人'
            show_txt = '仅剩名额'
        } else if (item.buys >= item.totals) {
            show_txt = ''
            showText = '已报满'
        } else {
            showText = item.buys + '人'
            show_txt = '已报名额'
        }
        return (
            <View style={styles.card}>
                <TouchableOpacity onPress={()=>this.goToCommonDetail(item)}>
                    <View style={{flex:1}}>
                        <Image source={{uri:item.image}}
                               style={styles.course_image}/>
                        <View style={styles.course_free_view}>
                            <Text style={styles.course_free_text}>免费</Text>
                        </View>
                    </View>
                    <Text numberOfLines={1} style={styles.course_title}>{item.title}</Text>
                    <View style={styles.course_teacher_contain}>
                        <Image style={styles.course_teacher_avatar}
                               source={{uri:item.teacher_image}}/>
                        <Text style={styles.course_teacher_name}>{item.teacher}</Text>
                        <View style={{flex:1}}/>
                        <Text style={{color:'#333333',fontSize:9,marginRight:10}}>{show_txt}</Text>
                    </View>

                    <View style={{flex:1}}/>


                    <View style={styles.course_teacher_contain}>
                        <Image style={styles.course_time_icon}
                               source={require('../../../res/img/select/select_time.png')}/>
                        <Text style={styles.course_time_text}>{start_time}</Text>
                        <View style={{flex:1}}/>
                        <Text style={{color:'rgba(219, 56, 67, 1)',fontSize:13,marginRight:10}}>{showText}</Text>
                    </View>
                </TouchableOpacity>
            </View>
        )
    }


    goToGoodDetail(item) {
        this.props.navigation.navigate('CourseDetailScene', {type: 0, info: item})

    }

    goToCommonDetail(item) {
        this.props.navigation.navigate('CourseDetailScene', {type: 1, info: item})
    }

    /**
     * 精品课列表Item
     * @param rowData
     * @returns {XML}
     */
    renderListItem = (rowData: any) => {
        let item = rowData.item;

        let start_time = item.start_date.substr(5, 5).replace('-', '月') + '日'
        let end_time = item.end_date.substr(5, 5).replace('-', '月') + '日'

        var showText = ''
        var show_txt = '仅剩'
        let ren = ''

        if (item.buys >= item.totals * 0.8 && item.buys < item.totals) {
            showText = item.remains
            show_txt = '仅剩'
            ren = '/' + item.totals + '人'
        } else if (item.buys >= item.totals) {
            show_txt = ''
            ren = ''
            showText = '已售罄'
        } else {
            showText = item.buys
            show_txt = '已报名'
            ren = '/' + item.totals + '人'
        }

        let mMount = item.amount == null ? 0 : parseInt(item.amount);
        let mPrice = item.price == null ? 0 : parseInt(item.price);

        return (
            <TouchableOpacity onPress={()=>this.goToGoodDetail(item)}>

                <View style={[styles.cell_container,{overflow: 'hidden'}]}>
                    <CornerLabel
                        alignment={'right'}
                        cornerRadius={36}
                        style={{backgroundColor: '#DB3843',}}
                        textStyle={{fontSize: 12, color: 'white',marginTop:8}}>
                        7.5折
                    </CornerLabel>
                    <View style={{flexDirection:'row',backgroundColor:'white',width:width-60}}>
                        <View style={{backgroundColor:'#db3843',borderRadius:2,padding:3,}}>
                            <Text style={{color:'#FFFFFF',fontWeight:'bold',fontSize:11,}}>{item.subject}</Text>
                        </View>
                        <View
                            style={{backgroundColor:'white',borderRadius:2,padding:2,marginLeft:6,borderColor:'#DB3843',borderWidth:1,marginRight:4}}>
                            <Text style={{color:'#DB3843',fontSize:11,}}>{item.tag}</Text>
                        </View>
                        <Heading1>{item.title}</Heading1>
                        {/*<View*/}
                        {/*style={{backgroundColor:'#835110',width:45,height:15,justifyContent:'center',alignItems:'center',flexDirection:'row',}}>*/}
                        {/*<View*/}
                        {/*style={{backgroundColor:'white',borderRadius:2,justifyContent:'center',alignItems:'center',height:12,flexDirection:'row',paddingLeft:5,paddingRight:5,paddingBottom:2,paddingTop:2}}>*/}
                        {/*<Text style={{color:'rgba(0,0,0,0.7)',fontSize:11,}}>{item.subject.charAt(0)}</Text>*/}
                        {/*</View>*/}
                        {/*<Text style={{fontSize:11,color:'white',marginLeft:4,}}>{item.tag.charAt(0)}</Text>*/}
                        {/*</View>*/}
                    </View>
                    <View style={styles.space}>
                        <Image style={{width:12,height:12}}
                               source={require('../../../res/img/select/select_time.png') }/>
                        <Heading3 style={{marginLeft:7}}>{start_time}到{end_time}</Heading3>
                    </View>
                    <View style={styles.other}>
                        <Image style={{width:28,height:28,borderRadius:14}} source={{uri:item.master_teacher.image}}/>
                        <View style={styles.name}>
                            <Tip2>讲师</Tip2>
                            <Tip>{item.master_teacher.name}</Tip>
                        </View>
                        <View style={styles.secondImg}>
                            <Image style={{width:28,height:28,borderRadius:14}}
                                   source={{uri:item.tutor_teacher.image}}/>
                            <View style={styles.name}>
                                <Tip2>辅导</Tip2>
                                <Tip>{item.tutor_teacher.name}</Tip>
                            </View>
                        </View>
                    </View>
                    <View style={styles.separatorLine}/>
                    <View style={styles.teacher}>
                        <View style={{flexDirection:'row',alignItems:'center'}}>
                            <Text style={styles.ming_e}>{show_txt}</Text>
                            <Text style={styles.ming_e_show}>{showText}</Text>
                            <Text style={styles.ming_e}>{ren}</Text>
                        </View>
                        <View style={{flex:1}}/>

                        {mMount > mPrice ?
                            <View style={{flexDirection:'row',alignItems:'center',marginRight:10}}>
                                <View
                                    style={{flexDirection:'row',alignItems:'center',position:'absolute',justifyContent:"center"}}
                                    onLayout={({nativeEvent:e})=>this.layout(e)}>
                                    <Text style={{color:'#999999',fontSize:10}}>原价</Text>
                                    <Image style={{width:4,height:5,marginTop:4,marginLeft:2,marginRight:2}}
                                           source={require('../../../res/img/order/order_bi.png')}/>
                                    <Text style={{color:'#999999',fontSize:12}}>{item.amount}</Text>
                                </View>
                                <View
                                    style={{width:40,height:1,backgroundColor:'#555555',alignItems:'center',}}/>
                            </View> : <View/>}
                    </View>
                    <View style={{marginTop:6,flexDirection:'row',alignItems:'center'}}>
                        <Text style={{color:'#333333',fontSize:11,}}>距离</Text>
                        <Text style={{color:'#db3843',fontSize:14}}>7.5</Text>
                        <Text style={{color:'#333333',fontSize:11,}}>折</Text>
                        <SelectRebateCountDown
                            // date={new Date()}
                            style={{marginTop:4}}
                            date="2018-07-11 12:00:00"
                            daysStyle={styles.reabte_text}
                            hoursStyle={styles.reabte_text}
                            minsStyle={styles.reabte_text}
                            secsStyle={styles.reabte_text}
                            // firstColonStyle={styles.colon}
                            // secondColonStyle={styles.colon}
                        />
                        <View style={{flex:1}}/>
                        <View style={{flexDirection:'row',marginRight:10,alignItems:'center'}}>
                            <Image style={{width:6,height:7,marginTop:7}}
                                   source={require('../../../res/img/select/select_price.png')}/>
                            <Text style={styles.price2}>{item.price}</Text>
                        </View>
                    </View>
                </View>
            </TouchableOpacity>
        )
    }

    layout = (e) => {
        console.log('===============', e)
        this.setState({text_height: e.layout.width})
    }

    goBack() {
        this.props.navigation.goBack()
    }

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    reabte_text: {
        color: '#db3843',
        fontSize: 14,
    },
    header: {
        flexDirection: `row`,
        alignItems: 'center',
        width: width,
        height: 56,
        backgroundColor: '#F9F9F9'
    },
    imageBack: {
        marginLeft: 12
    },
    btnSearch: {
        marginLeft: 12,
        marginRight: 13,
        borderRadius: 30,
        backgroundColor: '#D1D1D1',
        height: 25,
        width: 56,
        justifyContent: 'center',
        alignItems: 'center'
    },
    btnTag: {
        borderRadius: 30,
        backgroundColor: '#F0F2F5',
        height: 20,
        width: 64,
        justifyContent: 'center',
        alignItems: 'center',
        marginLeft: 12,
        marginRight: 12
    },
    inputStyle: {
        height: 25,
        flex: 1,
        borderColor: 'white',
        borderWidth: 0.1,
        fontSize: 10,
        marginLeft: 19,
        borderRadius: 20,
        paddingLeft: 21,
        paddingRight: 21,
        paddingBottom: 5,
        paddingTop: 5,
        backgroundColor: "#ebebeb"
    },
    searchLeft: {
        fontSize: 14,
        color: 'black',
        marginBottom: 12,
        fontWeight: 'bold'
    },
    searchRight: {
        fontSize: 12,
        color: '#999999',
        marginBottom: 12,
        marginRight: 24,
        marginTop: 17,
        marginLeft: 5
    },
    deleteHistory: {
        width: width,
        justifyContent: 'space-between',
        flexDirection: 'row',
        marginLeft: 12,
        flex: 1,
        marginRight: 12,
        alignItems: 'center'
    },
    course_image: {
        height: 100,
        width: 171,
        resizeMode: 'cover',
        borderRadius: 6,
        position: 'absolute',
    },
    course_free_view: {
        position: 'relative',
        marginLeft: 12,
        width: 39,
        height: 16,
        backgroundColor: 'black',
        justifyContent: 'center',
        alignItems: 'center',
    },
    course_free_text: {
        color: 'white',
        fontSize: 10,
    },
    course_title: {
        color: 'rgba(0,0,0,0.8)',
        fontSize: 14,
        marginLeft: 12,
        marginTop: 115,
        fontWeight: 'bold',
        marginRight: 12,
    },
    course_teacher_contain: {
        alignItems: 'center',
        flexDirection: 'row',
        marginTop: 10,
    },
    course_teacher_avatar: {
        height: 18,
        width: 18,
        resizeMode: 'cover',
        marginLeft: 12,
        borderRadius: 9,
    },
    course_teacher_name: {
        color: 'rgba(0,0,0,0.5)',
        fontWeight: 'bold',
        fontSize: 11,
        marginLeft: 5,
    },
    course_time_icon: {
        height: 10,
        width: 10,
        resizeMode: 'cover',
        marginLeft: 12,
    },
    course_time_text: {
        color: 'rgba(0,0,0,0.3)',
        fontSize: 9,
        marginLeft: 3,
    },
    course_bo_fang_Button: {
        width: 39,
        height: 15,
        marginRight: 12,
    },
    card: {
        width: 171,
        height: 200,
        borderColor: '#e7e7e7',
        borderWidth: 0.5,
        borderRadius: 10,
        shadowColor: '#e7e7e7',
        elevation: 1,
        margin: 6
    },
    teacher: {
        justifyContent: 'space-between',
        flexDirection: 'row',
        alignItems: 'center',
    },
    name: {
        marginLeft: 12,
        flexDirection: 'column',
    },
    space: {
        marginTop: 15,
        alignItems: 'center',
        flexDirection: 'row',
    },
    space2: {
        marginTop: 8,
        flexDirection: 'row',
        marginLeft: 30,
        alignItems: 'center'
    },
    other: {
        marginTop: 15,
        flexDirection: 'row',
        alignItems: 'center',
    },
    icon: {
        width: 28,
        height: 28,
        borderRadius: 14,
    },
    price_icon: {
        color: '#DB3843',
    },
    price: {
        color: '#DB3843',
        marginRight: 15,
    },
    price2: {
        color: 'rgba(197, 50, 60, 1)',
        fontSize: 19,
        fontWeight: '700',
        marginLeft: 6,
    },
    cell_container: {
        backgroundColor: 'white',
        margin: 12,
        marginVertical: 3,
        borderColor: '#e7e7e7',
        borderWidth: 0.5,
        borderRadius: 5,
        shadowColor: '#e7e7e7',
        shadowOffset: {width: 0.5, height: 0.5},
        shadowOpacity: 0.4,
        shadowRadius: 10,
        elevation: 1,
        padding: 15
    },
    cell_container2: {
        backgroundColor: 'white',
        marginVertical: 3,
        borderColor: '#e7e7e7',
        borderWidth: 0.5,
        borderRadius: 5,
        shadowColor: '#e7e7e7',
        shadowOffset: {width: 0.5, height: 0.5},
        shadowOpacity: 0.4,
        shadowRadius: 10,
        elevation: 1,
        margin: 15,
        height: 100,
        flexDirection: 'row'
    },
    separatorLine: {
        flex: 1,
        backgroundColor: 'rgba(0,0,0,0.1)',
        height: 1,
        marginTop: 15,
        marginBottom: 15
    },
    secondImg: {
        marginLeft: 30,
        flexDirection: 'row',
        alignItems: 'center'
    },
    score: {
        width: 27,
        height: 14,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#DB3843',
        borderRadius: 10,
        marginRight: 12,
        marginBottom: 12,
    },
    submit_btn: {
        borderRadius: 13,
        backgroundColor: '#DB3843',
        height: 18,
        width: 78,
        justifyContent: 'center',
        alignItems: 'center',
        marginRight: 100,
        marginBottom: 14
    },
    ming_e: {
        fontSize: 12,
        color: 'rgba(0,0,0,0.7)',
        fontWeight: '200',
    },
    ming_e_show: {
        fontSize: 14,
        color: '#db3843',
        fontWeight: 'bold',
    },
});
